import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an48 from '@mmstudio/an000048';
import an49 from '@mmstudio/an000049';
import { isYieldExpression } from '@babel/types';
import { tbattendance, tbcurriculum, tbcurriculums, tbstudent } from '../../../../atoms/db';

const logger = anylogger('pages/api/zllweapp/rollcall/s001.api');

export type Result = {
	ok: true;
	data: {
		classroom: any;
		totalnumber: any;
		teachername: any;
		start_section: any;
		end_section: any;
		majorname: any;
		classname: any;
	}[];
	coursename: Pick<ITbcurriculum, 'coursename'>;
} | {
	ok: false;
	message: string;
};

export type Message = {
	id: string;
}

/**
 * pages/api/zllweapp/rollcall/s001.api
 */
const handler = an48<Result>();

handler.post(async (req, res) => {
	try {
		logger.debug('msg body:', req.body);
		const { id } = req.body as Message;
		const data = await tbcurriculums()
			.select({
				classroom: 'curriculums.classroom',
				totalnumber: 'curriculums.totalnumber',
				teachername: 'curriculums.teachername',
				start_section: 'curriculums.start_section',
				end_section: 'curriculums.end_section',
				majorname: 'class.majorname',
				classname: 'class.classname'
			})
			.leftJoin('class', 'class.class_id', 'curriculums.class_id')
			.where({
				'curriculums.course_id': id
			});
		const coursename = await tbcurriculum().first('coursename').where({
			curriculum_id: id
		});

		const classid = await tbcurriculums().first('class_id').where({
			course_id: id
		});
		const db = an49();
		const student = await tbstudent().select({
			name: 'student.name',
			id: 'student.student_id',

			//**记录attendancestatus=1 的数量 */ 
			count: db.raw('count(attendance.*)'),
			//**记录 attendancestatus=2 的数量  */

		}).leftJoin('attendance', 'attendance.student_id', 'student.student_id').where({ attendancestatus: 1 })
			.groupBy('name', 'id').orderBy('student.student_id', 'asc');




		const absence = await tbstudent().select({
			id: 'student.student_id',
			count: db.raw('count(attendance.*)'),
		}).leftJoin('attendance', 'attendance.student_id', 'student.student_id').where({ attendancestatus: 2 })
			.groupBy('id').orderBy('student.student_id', 'asc');


		const student1 = absence.map((it1) => {
			return student.map((it2) => {
				return {
					name: it2.name,
					id: it2.id,
					count: it2.count,
					absence: it1.count
				};
			});
		});

		logger.debug('coursename', coursename);
		logger.debug('data', data);
		logger.debug('student', student);
		logger.debug('absence', absence);
		logger.debug('student1', student1);


		res.status(200).json({ ok: true, data, coursename });
	} catch (error) {
		logger.error(error);
		logger.trace(error);
		res.status(200).json({ ok: false, message: (error as Error).message });
	}
});

export const config = {} as PageConfig;

export default handler;
